package com.punai.config.sqlitedao;


import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.punai.common.exception.ServiceException;
import com.punai.common.utils.sqlite.SqliteUtils;
import com.punai.config.constants.PnConfigConstants;
import com.punai.config.domain.EngineerLinkTemplate;
import com.punai.config.sqlitedomain.ConfigEngineerClass;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.text.SimpleDateFormat;
import java.util.*;

@Component
public class ConfigEngineerClassRepository {
	@Autowired
	private SqliteUtils sqliteUtils;

	public List<ConfigEngineerClass> findByPidNull() throws ServiceException, NumberFormatException{
		String sql="SELECT engineerClass.* from TAB_CONFIG_ENGINEER_CLASS engineerClass where engineerClass.PARENT_ID is null order by engineerClass.sorting";
		List<ConfigEngineerClass> ConfigEngineerClasslist = new ArrayList<>();
		List<ConfigEngineerClass> list = sqliteUtils.selectListRecord(ConfigEngineerClass.class, sql);
		if (CollUtil.isNotEmpty(list)) {
			for (ConfigEngineerClass engineerClass : list) {
				engineerClass.setChildren(findchildren(engineerClass.getId()));
				engineerClass.setParent(findOne(engineerClass.getParentId()));
				ConfigEngineerClasslist.add(engineerClass);
			}
		}
		return ConfigEngineerClasslist;
	}
	private List<ConfigEngineerClass> findchildren(String pid) throws NumberFormatException{
		String sql="SELECT engineerClass.* from TAB_CONFIG_ENGINEER_CLASS engineerClass where engineerClass.PARENT_ID = '"+pid+"' order by engineerClass.sorting";
		List<ConfigEngineerClass> ConfigEngineerClasslist = new ArrayList<>();
		List<ConfigEngineerClass> list = sqliteUtils.selectListRecord(ConfigEngineerClass.class, sql);
		if (CollUtil.isNotEmpty(list)) {
			for (ConfigEngineerClass engineerClass : list) {
				engineerClass.setChildren(findchildren(engineerClass.getId()));
				ConfigEngineerClasslist.add(engineerClass);
			}
		}
		return ConfigEngineerClasslist;
	}
	public ConfigEngineerClass findOne(String id){
		String sql="SELECT engineerClass.* from TAB_CONFIG_ENGINEER_CLASS engineerClass where 1=1 ";
		if(StrUtil.isEmpty(id)){
			return null;
		}
		sql+="and engineerClass.ID ='"+id+"'";
		ConfigEngineerClass configEngineerClass = sqliteUtils.selectOneRecord(ConfigEngineerClass.class, sql);
		if (configEngineerClass != null) {
			configEngineerClass.setParent(findOne(configEngineerClass.getParentId()));
		}
		return configEngineerClass;
	}
	public ConfigEngineerClass findOneByCode(String code){
		String sql="SELECT engineerClass.* from TAB_CONFIG_ENGINEER_CLASS engineerClass where engineerClass.CODE ='"+code+"'";
		ConfigEngineerClass configEngineerClass = sqliteUtils.selectOneRecord(ConfigEngineerClass.class, sql);
		if (configEngineerClass != null) {
			configEngineerClass.setParent(findOne(configEngineerClass.getParentId()));
		}
		return configEngineerClass;
	}
	public ConfigEngineerClass findMaxSorting(){
		String sql="SELECT MAX(SORTING) SORTING FROM TAB_CONFIG_ENGINEER_CLASS";
		ConfigEngineerClass result = sqliteUtils.selectOneRecord(ConfigEngineerClass.class, sql);
		if (result == null) {
			result = new ConfigEngineerClass();
			result.setSorting(0);
		}
		return result;
	}
	public ConfigEngineerClass save(ConfigEngineerClass engineerClass) throws NumberFormatException{
		SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
		ConfigEngineerClass findOne = this.findOne(engineerClass.getId());
		String Sql=" insert into "
		  		+ "TAB_CONFIG_ENGINEER_CLASS(ID,NAME,CODE,PARENT_ID,FEATURE_TYPE,"
		  		+ "SORTING,CREATE_DATE,LAST_MODIFY,EDIT_STATE,SREACH_KEY,VERSION,IS_OLD) "
		  		+ "values(?,?,?,?,?,?,?,?,?,?,?,?) ";
		//initSqliteConnection();
		int rownumber=0;
		if(ObjectUtil.isNull(findOne)){
			ConfigEngineerClass maxClass = findMaxSorting();
			engineerClass.setEditState(PnConfigConstants.EDITSTATE.SAVESTATE.getType());
			engineerClass.setVersion(PnConfigConstants.ENTITY_VERSION);
			engineerClass.setId(IdUtil.fastUUID());
			Object[] args=new Object[] {
					engineerClass.getId(),
					engineerClass.getName(),
					engineerClass.getCode(),
					engineerClass.getParent()==null||StrUtil.isEmpty(engineerClass.getParent().getId())?engineerClass.getParentId():engineerClass.getParent().getId(),
					engineerClass.getFeatureType(),
					maxClass.getSorting() + 1,
					simpleDateFormat.format(new Date()),
					simpleDateFormat.format(new Date()),
					engineerClass.getEditState(),
					engineerClass.getSreachKey(),
					engineerClass.getVersion(),
					engineerClass.getOld()
				};
			 rownumber= sqliteUtils.execute(Sql, args);
		}else{
			Sql=" update TAB_CONFIG_ENGINEER_CLASS set NAME=?,CODE=?,PARENT_ID=?,"
					+ "FEATURE_TYPE=?,SORTING=?,CREATE_DATE=?,LAST_MODIFY=?,"
					+ "EDIT_STATE=?,SREACH_KEY=?,VERSION=?,IS_OLD=? "
					+ "where ID=? ";
			engineerClass.setCreateDate(findOne.getCreateDate());
			engineerClass.setEditState(PnConfigConstants.EDITSTATE.UPDATESTATE.getType());
			engineerClass.setVersion(findOne.getVersion()+1);
			  Object[] args=new Object[] {
						engineerClass.getName(),
						engineerClass.getCode(),
						engineerClass.getParentId(),
						engineerClass.getFeatureType(),
						engineerClass.getSorting(),
						simpleDateFormat.format(engineerClass.getCreateDate()),
						simpleDateFormat.format(new Date()),
						engineerClass.getEditState(),
						engineerClass.getSreachKey(),
						engineerClass.getVersion(),
						engineerClass.getOld(),
						engineerClass.getId()
					  };
			 rownumber= sqliteUtils.execute(Sql, args);
		}
		if(engineerClass.getFeatureType().equals("4")){
			String sel="select * from tab_config_link_template_engineer where engineer_class_code='"+engineerClass.getCode()+"'";
			String sql="delete from tab_config_link_template_engineer where engineer_class_code='"+engineerClass.getCode()+"'";
			//initSqliteConnection();
			List<Map<String, Object>> list = sqliteUtils.list(sel);
			rownumber= sqliteUtils.execute(sql);

			String templateIds = engineerClass.getTemplateIds();
			if(templateIds != null && templateIds != ""){
				String[] split = templateIds.split(",");
				for (String string : split) {
					String sqladd="insert into tab_config_link_template_engineer(template_id,engineer_class_code) values(?,?)";
					//initSqliteConnection();
					Object[] args=new Object[]{
							string,
							engineerClass.getCode()
					};
					rownumber= sqliteUtils.execute(sqladd,args);
				}
			}
		}
		  if(rownumber==0) {
			  throw new ServiceException("sqlite.message.addException");
		  }
		return engineerClass;
	}
	public void del(String id) throws ServiceException{
		String sql="delete from TAB_CONFIG_ENGINEER_CLASS where id='"+id+"'";
		int rownumber = sqliteUtils.execute(sql);
		if(rownumber==0) {
		  throw new ServiceException("sqlite.message.addException");
		}
	}
	/**
	 * 根据Id查找，但不查找子类
	 * @param id
	 * @return
	 */
	public ConfigEngineerClass findOneNoChildren(String id){
		SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
		String sql="SELECT engineerClass.* from TAB_CONFIG_ENGINEER_CLASS engineerClass where 1=1 ";
		if(StrUtil.isEmpty(id)){
			return null;
		}
		sql+="and engineerClass.ID ='"+id+"'";
		return sqliteUtils.selectOneRecord(ConfigEngineerClass.class, sql);
	}
	public List<ConfigEngineerClass> findProjectEngineerClass() {
		String sql="SELECT engineerClass.* from TAB_CONFIG_ENGINEER_CLASS engineerClass where engineerClass.FEATURE_TYPE='1' order by engineerClass.sorting";
		return sqliteUtils.selectListRecord(ConfigEngineerClass.class, sql);
	}

	public List<EngineerLinkTemplate> getLinkTemplateEngineer(String code) {
		String sql="select template_id,engineer_class_code as class_code  from tab_config_link_template_engineer where engineer_class_code='"+code+"'";
		return sqliteUtils.selectListRecord(EngineerLinkTemplate.class, sql);
	}
}
